package com.threeonemeeting.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.IDownloadCallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.ui.MessageBox;
import com.snda.lib.util.FileHelper;
import com.snda.lib.util.MiscHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.R;
import com.threeonemeeting.adapter.MeetingDataDocListAdapter;
import com.threeonemeeting.adapter.MeetingDataImageListAdapter;
import com.threeonemeeting.listview.DragRefreshListView;
import com.threeonemeeting.model.DownloadInfo;
import com.threeonemeeting.model.MeetingDataDocInfo;
import com.threeonemeeting.model.NetInfo;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.tab.MultiActivityTab;
import com.threeonemeeting.task.GetDocumentsImageListTask;
import com.threeonemeeting.task.GetDocumentsListTask;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.util.MiscUtil;
import com.threeonemeeting.util.TaskUtil;

public class MeetingDataListActivity extends BaseTabActivity implements
		OnClickListener, IDownloadCallBack, OnItemClickListener {

	public static final int TAB_FILE = 0;
	public static final int TAB_IMAGE = 1;
	public static final int TAB_AUDIO = 2;
	public static final int TAB_VIDEO = 3;
	private int mCurrentTabIndex = TAB_FILE;

	private Button mBtnFile = null;
	private Button mBtnImage = null;
	private Button mBtnAudio = null;
	private Button mBtnVideo = null;

	private int nMeetingId = 0;

	private DragRefreshListView listViewMeetingDataDocument = null;

	private MeetingDataDocListAdapter mAdapter;
	private MeetingDataImageListAdapter mImagesAdapter;

	private LinearLayout loadingLayout = null;
	private LinearLayout norecordLayout = null;
	private LinearLayout listLayout = null;
	private LinearLayout imageListLayout = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_meeting_data_list);
		MiscUtil.setBackBtnListener(this);
		nMeetingId = getIntent().getExtras().getInt("id");

		loadingLayout = (LinearLayout) findViewById(R.id.loading_layout);
		listLayout = (LinearLayout) findViewById(R.id.list_layout);
		norecordLayout = (LinearLayout) findViewById(R.id.norecord_layout);
		imageListLayout = (LinearLayout) findViewById(R.id.image_list_layout);

		mBtnFile = (Button) findViewById(R.id.file_button);
		mBtnImage = (Button) findViewById(R.id.image_button);
		mBtnAudio = (Button) findViewById(R.id.audio_button);
		mBtnVideo = (Button) findViewById(R.id.video_button);

		mBtnFile.setOnClickListener(this);
		mBtnImage.setOnClickListener(this);
		mBtnAudio.setOnClickListener(this);
		mBtnVideo.setOnClickListener(this);

		Button btnDownload = (Button) findViewById(R.id.download_button);
		btnDownload.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				startActivity("DownloadActivity");
			}

		});

		MiscUtil.showLoadingLayout(this);
		LinearLayout imageListLayout = (LinearLayout) this
				.findViewById(R.id.image_list_layout);
		imageListLayout.setVisibility(View.GONE);

		// 文档列表相关的布局
		mAdapter = new MeetingDataDocListAdapter(this);
		listViewMeetingDataDocument = (DragRefreshListView) findViewById(R.id.lv_doc);
		listViewMeetingDataDocument.setAdapter(mAdapter);
		listViewMeetingDataDocument.setOnItemClickListener(this);
		listViewMeetingDataDocument
				.setOnRefreshListener(new DragRefreshListView.OnRefreshListener() {
					public void onRefresh() {
						sendRequest(mCurrentTabIndex, true);
					}
				});
		setCurrentTab(TAB_FILE);
		sendRequest(0);

		// 图片相关的布局
		GridView gridViewMeetingDataImage = (GridView) findViewById(R.id.gv_meeting_data_image);
		mImagesAdapter = new MeetingDataImageListAdapter(this);
		gridViewMeetingDataImage.setAdapter(mImagesAdapter);
		gridViewMeetingDataImage.setOnItemClickListener(this);
	}

	protected void setCurrentTab(int tabIndex) {
		setTabButtonStatus(mCurrentTabIndex, false);
		setTabButtonStatus(tabIndex, true);
		mCurrentTabIndex = tabIndex;
	}

	public void onClick(View v) {
		if (v == mBtnFile) {
			if (mCurrentTabIndex == TAB_FILE) {
				return;
			}
			setCurrentTab(TAB_FILE);
			sendRequest(0);
		} else if (v == mBtnImage) {
			if (mCurrentTabIndex == TAB_IMAGE) {
				return;
			}
			setCurrentTab(TAB_IMAGE);
			sendImageRequest();
		} else if (v == mBtnAudio) {
			if (mCurrentTabIndex == TAB_AUDIO) {
				return;
			}
			setCurrentTab(TAB_AUDIO);
			sendRequest(2);
		} else if (v == mBtnVideo) {
			if (mCurrentTabIndex == TAB_VIDEO) {
				return;
			}
			setCurrentTab(TAB_VIDEO);
			sendRequest(3);
		}

		MiscUtil.showLoadingLayout(this);
	}

	private void setTabButtonStatus(int tabIndex, boolean focus) {

		switch (tabIndex) {
		case TAB_FILE:
			if (focus) {
				mBtnFile.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnFile.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_left_round_selected));
			} else {
				mBtnFile.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnFile.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_left_round_default));
			}
			break;

		case TAB_IMAGE:
			if (focus) {
				mBtnImage.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnImage.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_no_round_selected));
			} else {
				mBtnImage.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnImage.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_no_round_default));
			}
			break;
		case TAB_AUDIO:
			if (focus) {
				mBtnAudio.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnAudio.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_no_round_selected));
			} else {
				mBtnAudio.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnAudio.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_no_round_default));
			}
			break;
		case TAB_VIDEO:
			if (focus) {
				mBtnVideo.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnVideo.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_right_round_selected));
			} else {
				mBtnVideo.setTextAppearance(this,
						android.R.style.TextAppearance_Theme);
				mBtnVideo.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.btn_style_red_right_round_default));
			}
			break;

		default:
			break;
		}
	}

	private void sendRequest(int nMessageType) {
		sendRequest(nMessageType, false);
	}

	private void sendRequest(int nMessageType, boolean bRefresh) {
		GetDocumentsListTask task = new GetDocumentsListTask(
				MeetingDataListActivity.this, MeetingDataListActivity.this);
		task.setRefresh(bRefresh);
		Bundle params = new Bundle();
		params.putString("eid", String.valueOf(nMeetingId));
		params.putString(
				"uid",
				String.valueOf(DataCenter.getInstance().currentLoginUserInfo.nUserId));
		params.putString("pass",
				DataCenter.getInstance().currentLoginUserInfo.strPassword);
		params.putString("type", String.valueOf(nMessageType));
		TaskManager.addTask(task, params, true);
	}

	private void sendImageRequest() {
		GetDocumentsImageListTask task = new GetDocumentsImageListTask(
				MeetingDataListActivity.this, MeetingDataListActivity.this);
		Bundle params = new Bundle();
		params.putString("eid", String.valueOf(nMeetingId));
		params.putString(
				"uid",
				String.valueOf(DataCenter.getInstance().currentLoginUserInfo.nUserId));
		params.putString("pass",
				DataCenter.getInstance().currentLoginUserInfo.strPassword);
		params.putString("type", "1");
		TaskManager.addTask(task, params, true);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

		// 支持拖拉刷新，第一个为拖拉刷新区域
		int nIndex = arg2;

		if (arg0 instanceof ListView) {
			nIndex = nIndex - 1;

			MeetingDataDocInfo docInfo = mAdapter.getItem(nIndex);
			if (docInfo == null)
				return;
			showDialog(docInfo);

		} else if (arg0 instanceof GridView) {
			String strUrl = mImagesAdapter.getItem(nIndex);
			if (MiscHelper.isEmpty(strUrl) == true)
				return;

			strUrl = Const.URL.BASE_SERVER_URL + strUrl;

			Intent intent = new Intent(MeetingDataListActivity.this,
					PreviewImageActivity.class);
			Bundle b = new Bundle();
			b.putString("url", strUrl);
			intent.putExtras(b);
			startActivity(intent);
		}

	}

	// 通过Handler进行UI的更新
	Handler uiHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case 0:
				MessageBox.showToast(getApplicationContext(),
						"文件已经下载到本地，是否立即安装？");
				break;

			case 1:
				MessageBox.showToast(getApplicationContext(), "网络连接异常，下载失败");
				break;

			case 2:
				MessageBox.showToast(getApplicationContext(), "开始下载");
				break;

			case 3:
				String strPath = (String) msg.obj;
				MiscUtil.openDocument(MeetingDataListActivity.this, strPath);
				break;
			}
			super.handleMessage(msg);
		}
	};

	private void processDownloadFile(Map<String, Object> mapData) {

		Integer nError = (Integer) mapData.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {

			String strAppKey = (String) mapData.get("appkey");

			// 更新对应的状态为FAILED
			DownloadInfo dInfo = DataCenter.getInstance().listDownload
					.getDownloadInfo(strAppKey);
			if (dInfo != null) {
				dInfo.nStatus = DownloadInfo.DOWNLOAD_STATUS_FAILED;
				uiHandler.sendEmptyMessage(1);
			}

			return;
		}
	}

	/**
	 * @desc 已经安装
	 */
	public void onAlreadyDownloaded(String strPath) {
		Message msg = new Message();
		msg.what = 3;
		msg.obj = strPath;
		uiHandler.sendMessage(msg);
	}

	public void doCallBack(Map<String, Object> map) {
		Integer msgType = (Integer) map.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			Log.d(Const.Tag, "can't find type in response type");
			return;
		}

		Integer nError = (Integer) map.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {
			Log.d(Const.Tag, "response return error:" + nError + " type:"
					+ msgType);
			return;
		}

		if (msgType == HttpConst.TASKTYPE_DOWNLOADAPKFILE) {
			processDownloadFile(map);
			return;
		} else if (msgType == HttpConst.TASKTYPE_GETDOCUMENTLIST) {
			loadingLayout.setVisibility(View.GONE);

			@SuppressWarnings("unchecked")
			ArrayList<MeetingDataDocInfo> listDocument = (ArrayList<MeetingDataDocInfo>) map
					.get(Const.Keys.KEY_LIST);

			// 如果评论为空
			if (listDocument == null || listDocument.size() == 0) {
				norecordLayout.setVisibility(View.VISIBLE);
				listLayout.setVisibility(View.GONE);
				return;
			}

			norecordLayout.setVisibility(View.GONE);
			listLayout.setVisibility(View.VISIBLE);

			mAdapter.setDocumentList(listDocument);
			mAdapter.notifyDataSetChanged();

			listViewMeetingDataDocument.onRefreshComplete();

			return;
		} else if (msgType == HttpConst.TASKTYPE_GETDOCUMENTIMAGELIST) {

			loadingLayout.setVisibility(View.GONE);
			listLayout.setVisibility(View.GONE);

			@SuppressWarnings("unchecked")
			List<MeetingDataDocInfo> listDocument = (ArrayList<MeetingDataDocInfo>) map
					.get(Const.Keys.KEY_LIST);
			// 如果评论为空
			if (listDocument == null || listDocument.size() == 0) {
				norecordLayout.setVisibility(View.VISIBLE);
				listLayout.setVisibility(View.GONE);
				return;
			}

			norecordLayout.setVisibility(View.GONE);

			if (listDocument.size() == 0) {
				imageListLayout.setVisibility(View.GONE);
				norecordLayout.setVisibility(View.VISIBLE);
			} else {
				ArrayList<String> mImagesItems = new ArrayList<String>();
				for (int i = 0; i < listDocument.size(); i++) {
					mImagesItems.add(listDocument.get(i).strFileUrl);
				}

				mImagesAdapter.setImageList(mImagesItems);

				imageListLayout.setVisibility(View.VISIBLE);
				norecordLayout.setVisibility(View.GONE);
			}

			mImagesAdapter.notifyDataSetChanged();
		}
	}

	protected void showDialog(final MeetingDataDocInfo docInfo) {

		String strSize = FileHelper.getSizeDesc(docInfo.nFileSize);
		String strNetworkType = NetInfo.getInstance(this).getNetworkType();

		// 是wifi类型
		if (strNetworkType.equalsIgnoreCase("WiFi") == true) {

			// 开始下载
			TaskUtil.addDownloadTask(docInfo, MeetingDataListActivity.this);

		} else {
			DialogInterface.OnClickListener comfirmListener = new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// 开始下载
					TaskUtil.addDownloadTask(docInfo,
							MeetingDataListActivity.this);
				}
			};

			MessageBox box = new MessageBox(
					((MultiActivityTab) MeetingDataListActivity.this
							.getParent()));
			box.showDialog("确定下载吗?", "该文件大小为" + strSize
					+ "，您当前不是通过WiFi方式联网，确定下载吗？", comfirmListener);
		}
	}

	public void onClick(DialogInterface dialog, int which) {

	}

}
